package com.yonyou.pmclouds.basecom.interceptor;

import com.yonyou.pmclouds.basecom.util.StringUtils;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.builder.ToStringBuilder;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Enumeration;
import java.util.List;
import java.util.regex.Pattern;

/**
 * @author xiejianyu
 * 2019-08-27
 */
@Data
@Slf4j
public class PrintParamInterceptor implements HandlerInterceptor {

    /**
     * 是否输出cookies信息
     */
    @Value("${pmcloud.log.printRequestCookie}")
    private boolean outputCookie;

    /**
     * 忽略日志输出列表
     */
    private List<String> ignoredPaths;

    /**
     * 忽略日志输出正则列表
     */
    private List<Pattern> ignoredPatterns;

    @Override
    public boolean preHandle(HttpServletRequest request,
                             HttpServletResponse response, Object handler) throws Exception {
        try {
            if (log.isInfoEnabled()) {
                String uri = request.getRequestURI();

                //判断是否需要过滤
                if(StringUtils.ignorePattern(ignoredPatterns, uri))
                    return true;

                // 输出所有的参数
                StringBuilder sb = new StringBuilder(uri+"【参数】：");

                //上传的请求不打印参数
  //              if(request.getContentType()!=null&&request.getContentType().contains("multipart")){
  //                  sb.append("文件上传");
  //              } else {
                    Enumeration p = request.getParameterNames();
                    while (p.hasMoreElements()) {
                        String key = (String) p.nextElement();
                        String[] value = request.getParameterValues(key);
                        sb.append(key).append("=").append(array2String(value)).append(",");
                    }

                    // 输出cookie信息
                    if (outputCookie) {
                        sb.append("【cookies】:");
                        Cookie[] cookies = request.getCookies();
                        if (cookies != null) {
                            for (Cookie cookie : cookies) {
                                sb.append(cookie.getName()).append("=").append(ToStringBuilder.reflectionToString(cookie)).append(",");
                            }
                        }

                        Enumeration headers = request.getHeaderNames();
                        sb.append("【headers】:");
                        while (headers.hasMoreElements()) {
                            String key = (String) headers.nextElement();
                            String value = request.getHeader(key);
                            sb.append(key).append("=").append((value)).append(",");
                        }
                    }
 //               }
                log.info("【输入】:" + sb.toString());
            }
        } catch (Exception e) {
            log.error("异常信息：", e);
        }
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request,
                           HttpServletResponse response, Object handler,
                           ModelAndView modelAndView) throws Exception {
        // TODO Auto-generated method stub
    }

    @Override
    public void afterCompletion(HttpServletRequest request,
                                HttpServletResponse response, Object handler, Exception ex)
            throws Exception {
        // TODO Auto-generated method stub
    }

    private String array2String(String[] input){
        if(input.length==1){
            return input[0];
        }
        StringBuilder sb=new StringBuilder();
        sb.append("[");
        for (String string : input) {
            sb.append(string).append(",");
        }
        sb.append("]");
        return sb.toString();
    }

}